


#version 330 core

struct Material {
    sampler2D diffuse;
    sampler2D specular;
    float     shininess;
};

struct Light {
    //决定是位置光还是定向光
    vec4 lightVector;
    
    //灯的属性
    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
    
    //衰减常量
    float constant;
    float linear;
    float quadratic;
    
    //聚光灯属性
    vec3  position;
    vec3  direction;
    float cutOff;
};

out vec4 FragColor;

in vec3 Normal;
in vec3 FragPos;
in vec2 TexCoords;

uniform vec3 viewPos;

uniform Material material;
uniform Light light;

//聚光灯,手电筒
void main()
{
    vec3 lightDir;
    
    if(light.lightVector.w == 0.0)     //位置光
        lightDir = normalize(vec3(light.lightVector) - FragPos);
    else if(light.lightVector.w == 1.0)// 定向光
        lightDir = normalize(-vec3(light.lightVector));
    
    float theta = dot(lightDir, normalize(-light.direction));
    if(theta > light.cutOff) // remember that we're working with angles as cosines instead of degrees so a '>' is used.
    {
        // 环境光
        vec3 ambient  = light.ambient  * vec3(texture(material.diffuse, TexCoords));
    
        // 漫反射
        vec3 norm = normalize(Normal);// 执行定向光照计算
        float diff = max(dot(norm, lightDir), 0.0);
        vec3 diffuse  = light.diffuse  * diff * vec3(texture(material.diffuse, TexCoords));
    
        // 镜面光
        vec3 viewDir = normalize(viewPos - FragPos);
        vec3 reflectDir = reflect(-lightDir, norm);
        float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
        vec3 specular = light.specular * spec * vec3(texture(material.specular, TexCoords));
    
        float distance    = length(vec3(light.lightVector) - FragPos);
        float attenuation = 1.0 / (light.constant + light.linear * distance + light.quadratic * (distance * distance));
    
        ambient  *= attenuation;
        diffuse  *= attenuation;
        specular *= attenuation;
    
        vec3 result = ambient + diffuse + specular;
        FragColor = vec4(ambient + diffuse + specular, 1.0);
    }
    else
    {
        // else, use ambient light so scene isn't completely dark outside the spotlight.
        FragColor = vec4(light.ambient * texture(material.diffuse, TexCoords).rgb, 1.0);
    }
}

